import { db } from '@/lib/db';
import { user } from '@/lib/db/schema/auth';
import { result } from '@/lib/utils';
import { and, between, desc, eq, ilike, inArray, ne, or } from 'drizzle-orm';
import type { Pagination } from '../type/pagination';

export const listUsersByPage = async (args: {
  page: number;
  pageSize: number;
  id?: string;
  name?: string;
  email?: string;
  role?: string[];
  status?: string[];
  dateRange?: { from: Date; to?: Date };
}) => {
  try {
    const res = await db.query.user.findMany({
      where: and(
        args.id !== undefined ? eq(user.id, args.id) : undefined,
        args.name !== undefined
          ? ilike(user.name, `%${args.name}%`)
          : undefined,
        args.email !== undefined
          ? ilike(user.email, `%${args.email}%`)
          : undefined,
        args.role !== undefined ? inArray(user.role, args.role) : undefined,
        args.status?.length === 1
          ? args.status[0] === 'normal'
            ? ne(user.banned, true)
            : eq(user.banned, true)
          : undefined,
        args.dateRange !== undefined
          ? between(
              user.createdAt,
              args.dateRange.from,
              args.dateRange.to ? args.dateRange.to : new Date(),
            )
          : undefined,
      ),
      offset: (args.page - 1) * args.pageSize,
      limit: args.pageSize + 1,
      orderBy: desc(user.createdAt),
    });
    if (res.length > args.pageSize) {
      res.pop();
      return result({
        data: res,
        next: args.page + 1,
      } satisfies Pagination<(typeof res)[0]>);
    }
    return result({ data: res, next: null } satisfies Pagination<
      (typeof res)[0]
    >);
  } catch (error) {
    return result(error, '获取用户失败');
  }
};
